from django.http import HttpResponseBadRequest
from django.http import HttpResponseNotFound
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext

from tppt import importer

def perform_table_import(data):
	try:
		stats=importer.import_tables(data)
	except importer.ColumnNameError, name:
		return HttpResponseBadRequest('Invalid column name: "%s".' % name)
	except importer.InvalidReferencePrimaryKeyError, name:
		return HttpResponseBadRequest('Invalid reference primary key: "%s".' % name)
	except importer.InvalidModelNameError, name:
		return HttpResponseNotFound('Model not found: "%s".' % name)
	return stats

def machine_importer(request):
	if 'data' in request.FILES:
		data_string=request.FILES['data']['content']
		res=perform_table_import(data_string)
		if isinstance(res, HttpResponse):
			return res
		return HttpResponse('Ok. (%s added, %s updated)' % (res['added'], res['updated']))
	else:
		return HttpResponseBadRequest('No data.') 	

def upload_importer(request):
	params={}
	if 'data' in request.FILES:
		data_string=request.FILES['data']['content']
		res=perform_table_import(data_string)
		if isinstance(res, HttpResponse):
			return res
		params['result']='%s added, %s updated.' % (res['added'], res['updated'])
	return render_to_response('importer/upload.html', params, context_instance=RequestContext(request))

def result_importer(request):
	from tppt.importer import result  
	if 'data' in request.FILES:
		data_string=request.FILES['data']['content']
		try:
			result.import_result(data_string)
		except result.UnknownDetailType, key:
			return HttpResponseBadRequest('Unknown detail type: "%s".' % key)
		except result.InvalidFormat, line:
			return HttpResponseBadRequest('Invalid format: "%s".' % line)
		return HttpResponse('Ok.')
	else:
		return HttpResponseBadRequest('No data.') 	
